import { DeviceEventEmitter, NativeModules } from "react-native";
import XLog from "./XLog";
const { MQTTServerLibraryModule } = NativeModules;

const defaultOptions = {
    port: "1883",
    wsPort: "8080",
    host: "0.0.0.0",
    auth: false,
    userName: "",
    password: ""
}

export default class MQTTServer{
    static eventHandler = null;
    static startMQTTService(options, autoRestart, connectCallback, closeCallback) {
        const optionObj = {
            ...defaultOptions,
            ...options
        };
        if(this.eventHandler != null) {
            this.eventHandler.remove();
        }
        this.eventHandler = DeviceEventEmitter.addListener("mqtt_server_event", (data)=>{
            if(data.event == "connect" && connectCallback) {
                connectCallback(data);
            } else if(data.event == "close" && closeCallback) {
                closeCallback(data);
            } else {
                XLog.e("mqtt server error:", data);
            }
        });
        
        MQTTServerLibraryModule.startMQTTService(optionObj, autoRestart);
    }

    static stopMQTTService() {
        return new Promise((resolve, reject) => {
            if(this.eventHandler != null) {
                this.eventHandler.remove();
                this.eventHandler = null;
            }
            MQTTServerLibraryModule.stopMQTTService();
            let timerHandler = setTimeout(() => {
                clearTimeout(timerHandler);
                resolve(0);
            }, 500);
        });
    }

    static async getClientConnects() {
        return MQTTServerLibraryModule.getClientConnects();
    }

    static isMQTTServiceRunning() {
        return MQTTServerLibraryModule.isMqttServiceRunning();
    }
}